<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Model\CoinLog;
use App\Model\PayOrder;
use Encore\Admin\Grid;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Table;

class RechargeByCallController extends Controller
{
    use ModelForm;

    public function index()
    {
        $content = new Content();
        $content->header('通过速配通话的充值记录');
        $content->body($this->grid());
        return $content;
    }

    protected function grid()
    {
        $grid = new Grid(new CoinLog());
        $where = [
            'from' => CoinLog::FROM_DAILY_FREE_RECHARGE
        ];
        $grid->model()->where($where)->orderBy('id', 'desc');
        $grid->id('流水ID');
        $grid->userProfile()->user_profile_id('奖励女用户ID');
        $grid->userProfile()->nick_name('女用户昵称');
        $grid->coin('奖励金币数');
        $grid->opProfile()->user_profile_id('充值男用户ID');
        $grid->opProfile()->nick_name('充值男用户昵称')->modal('充值记录', function ($model) {
            $orders = $model->orders()->where(['status' => PayOrder::STATUS_OK])->orderby('id', 'desc')->take(10)->get()->map(function ($order) {
                return $order->only(['total_amount', 'recharge_coin', 'finished_at', 'id']);
            });
            $data = $orders->toArray();
            foreach ($data as &$item) $item['total_amount'] /= 100;
            return new Table(['充值金额', '金币数', '充值时间'], $data);
        });
        $grid->created_at('奖励时间')->display(function ($time) {
            return !$time ? '-' : date('Y-m-d H:i:s', strtotime($time));
        });
        $grid->disableExport();
        $grid->disableRowSelector();
        $grid->filter(function ($filter) {
            $filter->expand();
            $filter->disableIdFilter();
            $filter->column(1 / 3, function ($filter) {
                $filter->equal('userProfile.user_profile_id', '女用户ID');
            });
            $filter->column(1 / 3, function ($filter) {
                $filter->equal('opProfile.user_profile_id', '充值用户ID');
            });
        });
        $grid->disableActions();
        $grid->actions(function (Actions $actions) {
            $actions->disableDelete();
            $actions->disableView();
            $actions->disableEdit();
        });
        return $grid;
    }
}
